//package com.service.business.rabbitmq.listener;
//
//
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.service.business.base.service.ConfigService;
//import com.service.business.member.service.*;
//import com.service.business.order.service.OrderProductHrComboDetailsService;
//import com.service.business.order.service.OrderProductHrComboService;
//import com.service.business.rabbitmq.binding.OrderHrComboSink;
//import com.service.business.rabbitmq.service.SysMqRecordService;
//import com.service.business.rabbitmq.support.MqMsgLockUtils;
//import com.service.dao.dto.HrComboOrder;
//import com.service.dao.enums.HashRateOrderEnums;
//import com.service.dao.model.*;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.cloud.stream.annotation.EnableBinding;
//import org.springframework.cloud.stream.annotation.StreamListener;
//import org.springframework.stereotype.Component;
//import org.springframework.util.ObjectUtils;
//
//import java.math.BigDecimal;
//import java.util.Collections;
//import java.util.List;
//
//@Slf4j
//@Component
//@EnableBinding(OrderHrComboSink.class)
//public class OrderHrComboReceiveListener {
//
//	@Autowired
//	private ConfigService configService;
//	@Autowired
//	private MemberService memberService;
//	@Autowired
//	private MqMsgLockUtils mqMsgLockUtils;
//	@Autowired
//	private SysMqRecordService sysMqRecordService;
//	@Autowired
//	private MemberAwardByHrComboOrderService memberAwardService;
//	@Autowired
//	private OrderProductHrComboService orderProductHrComboService;
//	@Autowired
//	private OrderProductHrComboDetailsService detailsService;
//	@Autowired
//	private MemberCacheService memberCacheService;
//	@Autowired
//	private MemberGradeConfigService gradeConfigService;
//	@Autowired
//	private MemberJAService memberJAService;
//
//	public static BigDecimal baseNum = new BigDecimal(100L);
//
//	@StreamListener(target = OrderHrComboSink.IN_PAY_HR_COMBO_ORDER)
//	public void processPayHrComboOrder(HrComboOrder payOrder) {
//		log.info("receive hr combo order:{}", payOrder);
//		try {
//			if (mqMsgLockUtils.lockOrder(payOrder.getMsgId())) {
//				this.dealMemberAward(payOrder);
////				memberJAService.dealMemberAward(payOrder);
//				sysMqRecordService.confirmReceiveMsh(payOrder.getMsgId());
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			throw e;
//		} finally {
//			mqMsgLockUtils.unlockOrder(payOrder.getMsgId());
//		}
//
//	}
//
//	public void dealMemberAward(HrComboOrder payOrder) {
//		OrderProductHrCombo orderProductHrCombo = orderProductHrComboService.getById(payOrder.getOrderId());
//		if (ObjectUtils.isEmpty(orderProductHrCombo)) {
//			log.error("算力订单<orderId:{}>不存在", payOrder.getOrderId());
//			return;
//		}
//		if (!ObjectUtils.nullSafeEquals(orderProductHrCombo.getOrderSource(), HashRateOrderEnums.Source.RATE_MALL.getSourceCode())) {
//			log.error("算力订单<orderId:{}>非算力商城购买算力", payOrder.getOrderId());
//			return;
//		}
//		if (ObjectUtils.nullSafeEquals(orderProductHrCombo.getReleaseAward(), HashRateOrderEnums.ReleaseAwardStatus.RELEASE.getCode())) {
//			log.warn("算力订单<orderId:{}>已发送算力奖励", payOrder.getOrderId());
//			return;
//		}
//
//		Member member = memberService.getMemberById(orderProductHrCombo.getMemberId());
//		if (ObjectUtils.isEmpty(member)) {
//			log.warn("算力订单<orderId:{}>奖励发放失败，该会员已删除", payOrder.getOrderId());
//			return;
//		}
//		// 直推父级算力奖励
//		memberAwardService.sendMemberDRHashRate(orderProductHrCombo, member.getPid());
//		// 间推祖父级算力奖励
////		memberAwardService.sendMemberIRHashRate(orderProductHrCombo, member.getGid());
//		// 会员团队算力奖励
//		memberAwardService.sendMemberTeamHashRate(orderProductHrCombo, member);
////		upgradeByOrder(orderProductHrCombo);
//		orderProductHrComboService.updateById(OrderProductHrCombo.builder()
//				.id(payOrder.getOrderId())
//				.releaseAward(HashRateOrderEnums.ReleaseAwardStatus.RELEASE.getCode())
//				.build());
//	}
////	/**
////	 * @Description: 支付订单判断用户团队升级情况
////	 * @Author: ty
////	 * @Date: 2021/5/21 14:34
////	 * @param: [orderProductHrCombo]
////	 * @return: void
////	 **/
////	public void upgradeByOrder(OrderProductHrCombo combo) {
////		//判断订单是否是锚定产品
////		OrderProductHrComboDetails details = detailsService.getOne(new QueryWrapper<OrderProductHrComboDetails>().lambda()
////				.eq(OrderProductHrComboDetails::getHrOrderId, combo.getId())
////		);
////		if (ObjectUtils.isEmpty(details)) {
////			log.info("订单orderId:{}不是锚定产品退出等级升级策略", combo.getId());
////			return;
////		}
////		//获取用户所在团队列表
////		List<Member> teamList = memberService.selectByPathAndStatus(combo.getMemberId());
////		Member topMember = memberService.getMemberById(combo.getMemberId());
////		if(ObjectUtils.isEmpty(teamList)){
////			teamList = new ArrayList<>();
////		}
////		teamList.add(topMember);
////		teamList.parallelStream().forEach(member -> {
////			//判断用户是否升级
////			Integer memberId = member.getId();
////			if (ObjectUtils.isEmpty(member)) {
////				log.info("检查用户等级失败，用户不存在");
////				return;
////			}
////			MemberCache memberCache = memberCacheService.getMemberCache(memberId);
////			if (ObjectUtils.isEmpty(memberCache)) {
////				memberCacheService.initMemberCache4Register(member.getId(), member.getUserAccount());
////				memberCache = memberCacheService.getMemberCache(memberId);
////			}
////			//获取用户锚定消费累计
////			BigDecimal currentEarmarkProductConsumption = orderProductHrComboService.totalEarmarkOrderPvBy(memberId);
////			log.info("用户id:{},消费指定产品金额={}", member.getId(), currentEarmarkProductConsumption);
////			if(currentEarmarkProductConsumption.compareTo(BigDecimal.ZERO) > 0){
////				//判断用户消费所处的vip等级配置
////				MemberGradeConfig memberGradeConfig = gradeConfigService.getByTotalConsumption(currentEarmarkProductConsumption);
////				if (ObjectUtils.isEmpty(memberGradeConfig)) {
////					log.info("用户id:{},累计消费所处等级未找到", member.getId());
////				}else{
////					log.info("用户id:{},累计消费所处等级={}", member.getId(), memberGradeConfig.getId());
////					//等级是否允许自动升级
////					if (memberGradeConfig.getAutoUpdate() == GradleEnums.AutoUpdate.YES.getCode()) {
////						member.setVipGrade(memberGradeConfig.getId());
////					}
////					member.setNextVipGrade(memberGradeConfig.getId());
////				}
////			}
////
////			//2 判断用户伞下业绩
////			//获取用户直推列表
////			List<Member> directRecommendList = memberService.selectByPidAndStatus(memberCache.getMemberId());
////			if (ObjectUtils.isEmpty(directRecommendList)) {
////				log.info("当前用户memberId:{},没有直推用户列表", memberCache.getMemberId());
////				memberService.updateById(member);
////				//更新缓存
////				memberCache.setMemberGrade(member.getVipGrade());
////				memberCache.setMemberNextGrade(member.getNextVipGrade());
////				memberCacheService.setMemberCache(memberCache);
////				log.info("用户id:{}最终等级vipGrade={},下一个等级nextVipGrid={},缓存信息cache={}", member.getId(),member.getVipGrade(), member.getNextVipGrade(), memberCache);
////				return;
////			}
////			//统计各个小市场的累计消费
////			List<BigDecimal> totalUmbrellaEarmarkProductConsumptionList = new ArrayList<>();
////			directRecommendList.parallelStream().forEach(item -> {
////				//根据当前直推用户伞下的业绩(包括当前用户直推用户)
////				List<Member> umbrellaList = memberService.selectByPidAndStatus(item.getId());
////				umbrellaList.add(item);//包括计算自身业绩
////				List<Integer> umbrellaMemberIdList = umbrellaList.stream().map(Member::getId).collect(Collectors.toList());
////				BigDecimal totalItemUmbrellaEarmarkProductConsumption = orderProductHrComboService.totalEarmarkOrderPvByMemberIds(umbrellaMemberIdList);
////				if (totalItemUmbrellaEarmarkProductConsumption.compareTo(BigDecimal.ZERO) < 0) {
////					log.info("当前<memberId:{}>小市场业绩为0，不纳入统计范围", item.getId());
////					return;
////				}
////				totalUmbrellaEarmarkProductConsumptionList.add(totalItemUmbrellaEarmarkProductConsumption);//伞下业绩总集合
////			});
////			//判断伞下业绩是否为空
////			if (!ObjectUtils.isEmpty(totalUmbrellaEarmarkProductConsumptionList)) {
////				//计算伞下业绩之总和
////				BigDecimal sumUmbrellaMarketConsumption = sumUmbrellaMarketConsumption(totalUmbrellaEarmarkProductConsumptionList);
////				if (sumUmbrellaMarketConsumption.compareTo(BigDecimal.ZERO) == 0) {
////					log.info("用户:memberId={},伞下业绩为0，退出伞下业绩升级流程...", member.getId());
////					return;
////				}
////				log.info("用户:memberId={},伞下业绩之和为:{}+++++++", member.getId(), sumUmbrellaMarketConsumption);
////				//根据业绩查询所在等级配置
////				MemberGradeConfig umbrellaMemberGradeConfig = gradeConfigService.getByTotalUmbrellaConsumption(sumUmbrellaMarketConsumption);
////				if (ObjectUtils.isEmpty(umbrellaMemberGradeConfig)) {
////					log.info("用户：memberId={},伞下业绩不在等级配置范围内", member.getId());
////					return;
////				}
////				//计算小市场业绩之总和
////				BigDecimal totalAllSmallConsumption = removeUmbrellaLargestMarketConsumption(totalUmbrellaEarmarkProductConsumptionList);
////				log.info("用户：memberId={},伞下小市场业绩之和={}", member.getId(), totalAllSmallConsumption);
////				//判断小市场限制是否开始
////				if (umbrellaMemberGradeConfig.getOpenSmallMarketConsumptionLimit() == GradleEnums.OpenSmallMarketConsumptionLimit.CLOSE.getCode()) {
////					if (umbrellaMemberGradeConfig.getAutoUpdate() == GradleEnums.AutoUpdate.YES.getCode()) {
////						member.setVipGrade(umbrellaMemberGradeConfig.getId());
////					}
////					member.setNextVipGrade(umbrellaMemberGradeConfig.getId());
////				} else if (umbrellaMemberGradeConfig.getOpenSmallMarketConsumptionLimit() == GradleEnums.OpenSmallMarketConsumptionLimit.OPEN.getCode()) {
////					BigDecimal sufficeScale = MathUtil.div(umbrellaMemberGradeConfig.getSmallMarketConsumptionQualifiedRate(), baseNum, 4);
////					BigDecimal sufficeConsumption = MathUtil.mul(sumUmbrellaMarketConsumption, sufficeScale, 8);
////					log.info("用户：memberId={},伞下小市场业绩达标比例={}%，总业绩={}，小市场业绩={}", member.getId(), sufficeScale, sumUmbrellaMarketConsumption, totalAllSmallConsumption);
////					if (totalAllSmallConsumption.compareTo(sufficeConsumption) >= 0) {
////						if (umbrellaMemberGradeConfig.getAutoUpdate() == GradleEnums.AutoUpdate.YES.getCode()) {
////							member.setVipGrade(umbrellaMemberGradeConfig.getId());
////						}
////						member.setNextVipGrade(umbrellaMemberGradeConfig.getId());
////					}
////				}
////			}
////			memberService.updateById(member);
////			//更新缓存
////			memberCache.setMemberGrade(member.getVipGrade());
////			memberCache.setMemberNextGrade(member.getNextVipGrade());
////			memberCacheService.setMemberCache(memberCache);
////			log.info("用户最终等级vipGrade={},下一个等级nextVipGrid={},缓存信息cache={}", member.getVipGrade(), member.getNextVipGrade(), memberCache);
////		});
////	}
//
//	/**
//	 * @Description: 计算小市场业绩之和
//	 * @Author: ty
//	 * @Date: 2021/4/26 16:13
//	 * @param: [totalUmbrellaEarmarkProductConsumptionList]
//	 * @return: java.math.BigDecimal
//	 **/
//	public BigDecimal sumUmbrellaMarketConsumption(List<BigDecimal> totalUmbrellaEarmarkProductConsumptionList) {
//		//计算小市场业绩之和
//		BigDecimal totalSmallMarketConsumption = totalUmbrellaEarmarkProductConsumptionList.stream().map(consumption -> {
//			if (consumption.compareTo(BigDecimal.ZERO) == 0) {
//				return BigDecimal.ZERO;
//			} else {
//				return consumption;
//			}
//		}).reduce(BigDecimal.ZERO, BigDecimal::add);
//		return totalSmallMarketConsumption;
//	}
//
//	/**
//	 * @Description: 去掉最大的小市场 返回其余的小市场之和
//	 * @Author: ty
//	 * @Date: 2021/4/26 16:13
//	 * @param: [totalUmbrellaEarmarkProductConsumptionList]
//	 * @return: java.math.BigDecimal
//	 **/
//	public BigDecimal removeUmbrellaLargestMarketConsumption(List<BigDecimal> totalUmbrellaEarmarkProductConsumptionList) {
//		//这里去掉最大小市场业绩
//		if (!ObjectUtils.isEmpty(totalUmbrellaEarmarkProductConsumptionList)) {
//			Collections.sort(totalUmbrellaEarmarkProductConsumptionList, Collections.reverseOrder());
//			totalUmbrellaEarmarkProductConsumptionList.remove(totalUmbrellaEarmarkProductConsumptionList.stream().findFirst().get());
//			//计算其他小市场业绩之和
//			BigDecimal totalSmallMarketConsumption = totalUmbrellaEarmarkProductConsumptionList.stream().map(consumption -> {
//				if (consumption.compareTo(BigDecimal.ZERO) == 0) {
//					return BigDecimal.ZERO;
//				} else {
//					return consumption;
//				}
//			}).reduce(BigDecimal.ZERO, BigDecimal::add);
//			return totalSmallMarketConsumption;
//		}
//		return BigDecimal.ZERO;
//	}
//}
